/**
 * Created by XianTao on 2016/11/14
 * <p/>
 * Copyright (c) 2015-2015
 * Apache License
 * Version 2.0, January 2004
 * http://www.apache.org/licenses/
 */
package org.lego.wechat.base.api;

import org.lego.handle.exception.ExtraInvalidParameterException;
import org.lego.util.ApiResult;
import org.lego.util.DateTimeUtil;
import org.lego.util.HttpUtil;
import org.lego.wechat.base.entity.WxJsAccessToken;
import org.lego.wechat.base.service.WxJsAccessTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 网页授权
 */
@Component
public class JsAccessTokenApi {
    @Autowired
    private WxJsAccessTokenService wxJsAccessTokenService;

    private String url = "https://api.weixin.qq.com/sns/oauth2/access_token";
    private String qyUrl = "";

    public synchronized WxJsAccessToken getJsAccessTokenByCode(String corpId, Integer agentId, String corpSecret, String code) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("appid", corpId);
        params.put("secret", corpSecret);
        params.put("code", code);
        params.put("grant_type", "authorization_code");
        ApiResult apiResult = ApiResult.create(HttpUtil.get(url, params));
        if (!apiResult.isSucceed()) {
            throw new ExtraInvalidParameterException("WechatSystem.api.errorCode", String.valueOf(apiResult.getErrorCode()));
        }
        String openId = apiResult.getStr("openid");
        WxJsAccessToken currentWxJsAccessToken = wxJsAccessTokenService.findOneByCorpIdAndAgentIdAndOpenId(corpId, agentId, openId);
        if (ObjectUtils.isEmpty(currentWxJsAccessToken)) {
            currentWxJsAccessToken = new WxJsAccessToken();
            currentWxJsAccessToken.setCorpId(corpId);
            currentWxJsAccessToken.setAgentId(agentId);
            currentWxJsAccessToken.setOpenId(openId);
        }
        currentWxJsAccessToken.setJsAccessToken(apiResult.getStr("access_token"));
        currentWxJsAccessToken.setCreateTime(DateTimeUtil.getCurrentTimeSeconds());
        currentWxJsAccessToken.setExpiredTime(currentWxJsAccessToken.getCreateTime() + apiResult.getInt("expires_in"));
        currentWxJsAccessToken.setRefreshToken(apiResult.getStr("refresh_token"));
        currentWxJsAccessToken.setScope(apiResult.getStr("scope"));
        currentWxJsAccessToken.setUnionId(apiResult.getStr("unionid"));
        wxJsAccessTokenService.saveAndFlush(currentWxJsAccessToken);
        return currentWxJsAccessToken;
    }
}
